package com.chengliang.bbs.point;

import com.chengliang.bbs.entry.JSONResult;
import com.chengliang.bbs.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;




/**
 * @author: chengliang
 * @create: 2019-08-14 11:38
 */
@Slf4j
@Component
public class MyLoginUrlAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        String requestType = httpServletRequest.getHeader("X-Requested-With");
        if(StringUtil.AJAX_REQUEST_TYPE.equals(requestType)){
            httpServletResponse.setContentType("application/json;charset=utf-8");
            PrintWriter out = httpServletResponse.getWriter();
            out.write(JSONResult.success("请进行登录").append("data","").append("action","/user/login").append("collection",false).toString());
            out.flush();
            out.close();
            return;
        }
        //跳转登录页
        httpServletResponse.sendRedirect("/user/login");
    }

}

